package api

import (
	"config-client-v1/init/global"
	"config-client-v1/model"
	"config-client-v1/utils/tools"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"path/filepath"
)

type TestController struct {
}

func (con TestController) Test(ctx *gin.Context) {
	//idStr := ctx.Query("id")
	//id, err := strconv.Atoi(idStr)
	//if err != nil {
	//	ctx.JSON(200, gin.H{
	//		"code":    1,
	//		"message": "id必须为数字",
	//	})
	//	return
	//}
	//err = model.DB.Transaction(func(tx *gorm.DB) error {
	//	err = tx.Where("id = ?", id).Delete(&model.VarRecord{}).Error
	//	if err != nil {
	//		return err
	//	}
	//	err = tx.Where("id = ?", id+1).Delete(&model.VarRecord{}).Error
	//	if err != nil {
	//		return err
	//	}
	//	return nil
	//})
	//if err != nil {
	//	ctx.JSON(200, gin.H{
	//		"code":    10,
	//		"message": "删除失败",
	//	})
	//	return
	//}
	ctx.JSON(200, gin.H{
		"code":    0,
		"message": "success",
	})
}

func (con TestController) FrameSaveContent(ctx *gin.Context) {
	protocol := ctx.Query("protocol") // 协议 RS485,MODBUS RTU,MODBUS TCP
	funcCode := ctx.Query("funcCode") // modbus 专用功能码
	fileNum := ctx.Query("fileNum")   // 协议编号
	if fileNum == "" {
		fileNum = "1"
	}
	content := make([]*model.FrameItemParam, 0)
	fileName := ""
	switch protocol {
	case "CAN":
		fileName = filepath.Join(global.StaticPath, "mock/frame_content", "can-"+fileNum+".json")
	case "RS232":
		fileName = filepath.Join(global.StaticPath, "mock/frame_content", "rs232-"+fileNum+".json")
	case "RS485":
		fileName = filepath.Join(global.StaticPath, "mock/frame_content", "rs485-"+fileNum+".json")
	case "MODBUS":
		fileName = filepath.Join(global.StaticPath, "mock/frame_content", "modbus-"+funcCode+"-"+fileNum+".json")
	case "TCP/IP":
		fileName = filepath.Join(global.StaticPath, "mock/frame_content", "tcp-"+fileNum+".json")
	case "PLCS7":
		fileName = filepath.Join(global.StaticPath, "mock/frame_content", "plcs7-"+fileNum+".json")
	default:
		ctx.JSON(200, gin.H{
			"code":    2,
			"message": "暂不支持当前 protocol",
			"data": map[string]interface{}{
				"可用protocol": model.AllowProtocol,
			},
		})
		return
	}
	str1, err := tools.ReadFileContent(fileName)
	if err != nil {
		ctx.JSON(200, gin.H{
			"code":    1,
			"message": "读取文件失败",
			"data":    err.Error(),
		})
		return
	}
	err = json.Unmarshal([]byte(str1), &content)
	if err != nil {
		ctx.JSON(200, gin.H{
			"code":    1,
			"message": "json解析文件失败",
			"data":    err.Error(),
			"tmp":     str1,
		})
		return
	}
	jsonBytes, _ := json.Marshal(&content)
	ctx.JSON(200, gin.H{
		"code":    0,
		"message": "success",
		"data": map[string]interface{}{
			"content": content,
			"json":    string(jsonBytes),
		},
	})

}

func (con TestController) FrameSendCondition(ctx *gin.Context) {
	content := make([]*model.FrameTriggerCondition, 0)
	fileName := filepath.Join(global.StaticPath, "mock/frame", "frame-send-condition.json")
	str1, err := tools.ReadFileContent(fileName)
	if err != nil {
		ctx.JSON(200, gin.H{
			"code":    1,
			"message": "读取文件失败",
			"data":    err.Error(),
		})
		return
	}
	err = json.Unmarshal([]byte(str1), &content)
	if err != nil {
		ctx.JSON(200, gin.H{
			"code":    1,
			"message": "json解析文件失败",
			"data":    err.Error(),
			"tmp":     str1,
		})
		return
	}
	jsonBytes, _ := json.Marshal(&content)
	ctx.JSON(200, gin.H{
		"code":    0,
		"message": "success",
		"data": map[string]interface{}{
			"content": content,
			"json":    string(jsonBytes),
		},
	})

}

func (con TestController) PPESaveConfig(ctx *gin.Context) {
	protocol := ctx.Query("protocol") // 协议 RS485,MODBUS RTU,MODBUS TCP
	var config interface{}
	switch protocol {
	case "RS232":
		fallthrough
	case "RS485":
		config = model.Rs485Config{
			PortName:        "COM1",
			BaudRate:        9600,
			DataBits:        8,
			StopBits:        1,
			ParityMode:      0,
			MinimumReadSize: 4,
			WorkFlow:        0,
		}
	case "MODBUS TCP":
		config = model.ModbusTCPConfig{
			Mode:            "client",
			IP:              "192.168.1.19",
			Port:            502,
			ConnectTimeout:  3000,
			ResponseTimeout: 1000,
		}
	case "MODBUS RTU":
		config = model.ModbusRTUConfig{
			PortName:        "COM9",
			BaudRate:        9600,
			DataBits:        8,
			StopBits:        1,
			ParityMode:      0,
			MinimumReadSize: 4,
			ConnectTimeout:  3000,
			ResponseTimeout: 1000,
		}
	case "TCP/IP":
		config = model.TCPIPConfig{
			Mode: "client",
			IP:   "192.168.1.19",
			Port: 8124,
		}
	case "PLCS7":
		config = model.PLCConfig{
			Type:    "S7-1500",
			IP:      "192.168.1.55",
			Port:    102,
			PDU:     1,
			CPURack: 1,
			CPUSlot: 1,
			Endian:  "big",
		}
	default:
		ctx.JSON(200, gin.H{
			"code":    2,
			"message": "暂不支持当前 protocol",
			"data": map[string]interface{}{
				"可用protocol": model.AllowProtocol,
			},
		})
		return
	}
	jsonBytes, _ := json.Marshal(config)
	ctx.JSON(200, gin.H{
		"code":    0,
		"message": "success",
		"data": map[string]interface{}{
			"config": config,
			"json":   string(jsonBytes),
		},
	})

}

func (con TestController) ModelSaveContent(ctx *gin.Context) {
	moduleType := ctx.Query("module_type")
	f := filepath.Join(global.StaticPath, "mock/fs_model/"+moduleType+".json")
	str, err := tools.ReadFileContent(f)
	if err != nil {
		ctx.JSON(200, gin.H{
			"code":    1,
			"message": "读取文件失败",
			"data": map[string]interface{}{
				"err": err.Error(),
				"可用选范围": []string{
					"bengzu",
					"zengya",
					"diantiao",
					"yali",
					"power",
					"powerState",
					"mode",
					"diag",
				},
			},
		})
		return
	}
	var content interface{}
	switch moduleType {
	case "bengzu":
		data := model.BengzuModel{}
		_ = json.Unmarshal([]byte(str), &data)
		content = data
	case "zengya":
		data := model.ZengyaModel{}
		_ = json.Unmarshal([]byte(str), &data)
		content = data
	case "diantiao":
		data := model.DiantiaoSVModel{}
		_ = json.Unmarshal([]byte(str), &data)
		content = data
	case "yali":
		data := model.PressureSVModel{}
		_ = json.Unmarshal([]byte(str), &data)
		content = data
	case "power":
		data := model.PowerModel{}
		_ = json.Unmarshal([]byte(str), &data)
		content = data
	case "powerState":
		data := model.PowerStateModel{}
		_ = json.Unmarshal([]byte(str), &data)
		content = data
	case "mode":
		data := model.ModeCollectModel{}
		_ = json.Unmarshal([]byte(str), &data)
		content = data
	case "diag":
		data := model.DiagModel{}
		_ = json.Unmarshal([]byte(str), &data)
		content = data
	default:
		ctx.JSON(200, gin.H{
			"code":    1,
			"message": "default error",
		})
		return
	}
	jsonBytes, _ := json.Marshal(content)
	ctx.JSON(200, gin.H{
		"code":    0,
		"message": "success",
		"data": map[string]interface{}{
			"content": content,
			"json":    string(jsonBytes),
		},
	})
}

func (con TestController) Cmd0603ModifyContent(ctx *gin.Context) {
	content := make([]*model.DataPart0604, 0)
	f := filepath.Join(global.StaticPath, "mock/cmd0603.json")
	str, err := tools.ReadFileContent(f)
	if err != nil {
		ctx.JSON(200, gin.H{
			"code":    1,
			"message": "读取文件失败",
		})
		return
	}
	err = json.Unmarshal([]byte(str), &content)
	if err != nil {
		ctx.JSON(200, gin.H{
			"code":    2,
			"message": "json解析失败",
		})
		return
	}
	jsonBytes, _ := json.Marshal(content)
	ctx.JSON(200, gin.H{
		"code":    0,
		"message": "success",
		"data": map[string]interface{}{
			"content": content,
			"json":    string(jsonBytes),
		},
	})
}

func (con TestController) ModbusDBSaveContent(ctx *gin.Context) {
	fileNum := ctx.Query("fileNum") // 协议编号
	if fileNum == "" {
		fileNum = "1"
	}
	content := make([]*model.ModbusPointBind, 0)
	fileName := ""
	fileName = filepath.Join(global.StaticPath, "mock/frame_content", "modbus-db-"+fileNum+".json")

	str1, err := tools.ReadFileContent(fileName)
	if err != nil {
		ctx.JSON(200, gin.H{
			"code":    1,
			"message": "读取文件失败",
			"data":    err.Error(),
		})
		return
	}
	err = json.Unmarshal([]byte(str1), &content)
	if err != nil {
		ctx.JSON(200, gin.H{
			"code":    1,
			"message": "json解析文件失败",
			"data":    err.Error(),
			"tmp":     str1,
		})
		return
	}
	jsonBytes, _ := json.Marshal(&content)
	ctx.JSON(200, gin.H{
		"code":    0,
		"message": "success",
		"data": map[string]interface{}{
			"content": content,
			"json":    string(jsonBytes),
		},
	})

}
